package org.dromara.patrol.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.patrol.domain.PatrolReportVerify;
import org.dromara.patrol.domain.bo.PatrolReportVerifyBo;
import org.dromara.patrol.domain.vo.PatrolReportVerifyVo;
import org.dromara.patrol.mapper.PatrolReportVerifyMapper;
import org.dromara.patrol.service.IPatrolReportVerifyService;
import org.dromara.system.api.RemoteUserService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 巡店管理-巡店报告整改审核Service业务层处理
 *
 * @author han
 * @date 2024-03-29
 */
@RequiredArgsConstructor
@Service
public class PatrolReportVerifyServiceImpl implements IPatrolReportVerifyService {

    private final PatrolReportVerifyMapper baseMapper;
    @DubboReference
    private RemoteUserService remoteUserService;

    /**
     * 查询巡店管理-巡店报告整改审核
     */
    @Override
    public PatrolReportVerifyVo queryById(Long verifyId){
        return baseMapper.selectVoById(verifyId);
    }

    /**
     * 查询巡店管理-巡店报告整改审核列表
     */
    @Override
    public TableDataInfo<PatrolReportVerifyVo> queryPageList(PatrolReportVerifyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatrolReportVerify> lqw = buildQueryWrapper(bo);
        Page<PatrolReportVerifyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<PatrolReportVerifyVo> rows = result.getRecords();
        if (CollUtil.isNotEmpty(rows)) {
            // 构建整改人名称
            buildNameMap(rows);
            result.setRecords(rows);
        }

        return TableDataInfo.build(result);
    }

    private void buildNameMap(List<PatrolReportVerifyVo> rows) {
        // 查询用户名称
        List<Long> userIds = StreamUtils.toSet(rows, PatrolReportVerifyVo::getCreateBy).stream().toList();
        Map<Long, String> userMap = remoteUserService.selectNickNameByIds(userIds);

        rows.forEach(row-> {
            Map<String, String> nameMap = new HashMap<>();
            // 执行人名称
            addIfNotNull(nameMap, row.getCreateBy(), userMap);
            row.setNameMap(nameMap);
        });
    }

    /**
     * 查询巡店管理-巡店报告整改审核列表
     */
    @Override
    public List<PatrolReportVerifyVo> queryList(PatrolReportVerifyBo bo) {
        LambdaQueryWrapper<PatrolReportVerify> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatrolReportVerify> buildQueryWrapper(PatrolReportVerifyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PatrolReportVerify> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getReportId() != null, PatrolReportVerify::getReportId, bo.getReportId());
        lqw.eq(bo.getNodeId() != null, PatrolReportVerify::getNodeId, bo.getNodeId());
        lqw.eq(bo.getRectifyId() != null, PatrolReportVerify::getRectifyId, bo.getRectifyId());
        lqw.eq(StringUtils.isNotBlank(bo.getVerifyStatus()), PatrolReportVerify::getVerifyStatus, bo.getVerifyStatus());
        return lqw;
    }

    /**
     * 新增巡店管理-巡店报告整改审核
     */
    @Override
    public Boolean insertByBo(PatrolReportVerifyBo bo) {
        PatrolReportVerify add = MapstructUtils.convert(bo, PatrolReportVerify.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setVerifyId(add.getVerifyId());
        }
        return flag;
    }

    /**
     * 修改巡店管理-巡店报告整改审核
     */
    @Override
    public Boolean updateByBo(PatrolReportVerifyBo bo) {
        PatrolReportVerify update = MapstructUtils.convert(bo, PatrolReportVerify.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PatrolReportVerify entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除巡店管理-巡店报告整改审核
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 向map中添加一个键值对，如果键不为null，则将该键及其对应的值从source map中获取，并添加到目标map中，
     * 如果source map中不存在该键，则将该键与空字符串对应，添加到目标map中。
     *
     * @param map    目标map
     * @param key    要添加的键
     * @param source 源map
     */
    private <K> void addIfNotNull(Map<String, String> map, K key, Map<K, String> source) {
        if (key != null) {
            map.put(key.toString(), source.getOrDefault(key, ""));
        }
    }
}
